package com.loveto.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loveto.common.ImageDownloader;
import com.loveto.common.JsonUtils;
import com.loveto.constant.LovetoConstant;
import com.loveto.constant.LovetoGiftAnims;
import com.loveto.model.CompetitorInfo;
import com.loveto.model.GiftInfo;

public class SlideshowWinner23RoundActivity extends BaseActivity implements
View.OnClickListener{
	
	// 사용하는 변수들
	private Integer roundSeq; // 라운드
	private String tournamentID; // 토너먼트 아이디
	private Map<Integer, List<CompetitorInfo>> CompetitorInfoMap; // 경쟁자 정보
	private int currentGroupNum; // 현재 그룹
	private int groupSize; // 그룹사이즈 
	private List<RelativeLayout> oneMemberLayoutList; // 참여자 카드들
	private List<RelativeLayout> oneMemberInfoLayoutList; // 참여자 카드들 info(2round이상만 쓰임)
	private RelativeLayout v_content_main_outer;
	private Integer totalCompetitorSize;
	private ArrayList<String> winnerIDList; // 진출자 IDs
	private ArrayList<String> firstRoundWinnerIDList;
	private ArrayList<String> secondRoundWinnerIDList;
	private ArrayList<String> thirdoundWinnerIDList;
	private ArrayList<String> fourthRoundWinnerIDList;
	private ProgressDialog progressDialog;
	private Handler myHandler;
	private LovetoGiftAnims giftAnims;
	private List<AnimationDrawable> giftAnimList;
	private List<GiftInfo> giftInfoList = new ArrayList<GiftInfo>();
	private String connectorMemberid; // 접속자 아이디
	private String connectorNextround_pass_yn; // 접속자 다음라운드 진출 여부
	private Integer connectorGiftid; // 접속자가 준 선물
	
	// btns
	private RelativeLayout btn_prev_round;
	private RelativeLayout btn_prev_group;
	private RelativeLayout btn_next_group;
	private RelativeLayout btn_next_round;
	
	// animation
	private boolean isNowAnimation;
	private int presentWinner;
	private Animation animRing;
	private Animation animText;
	private Animation animPhotoWinner;
	private Animation animPhotoLoser;
	private Animation animWhole;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_slideshow_winner_23round);
		
		//전 엑티비티에서 토너먼트ID, 라운드시퀀스 받아오기
		getTournamentIDAndRoundSeq();
		
		// Round 글자 수정
		TextView textView = (TextView) findViewById(R.id.textView1);
		textView.setText(roundSeq+"ROUND");
		
		// 초기화
		progressDialog = new ProgressDialog(this);
		giftAnims = new LovetoGiftAnims();
		myHandler = new Handler();
		giftAnimList = new ArrayList<AnimationDrawable>();
		winnerIDList = new ArrayList<String>();
		currentGroupNum = 0; // 현재 그룹 넘버
		CompetitorInfoMap = new HashMap<Integer, List<CompetitorInfo>>(); // 데이터들
		connectorNextround_pass_yn = "N";
		connectorGiftid = 0;
		isNowAnimation = false;
		
		oneMemberLayoutList = new ArrayList<RelativeLayout>();
		oneMemberLayoutList.add((RelativeLayout) findViewById(R.id.first_row_first_layout));
		oneMemberLayoutList.add((RelativeLayout) findViewById(R.id.first_row_second_layout));
		
		oneMemberInfoLayoutList = new ArrayList<RelativeLayout>();
		oneMemberInfoLayoutList.add((RelativeLayout) findViewById(R.id.first_userinfo_layout));
		oneMemberInfoLayoutList.add((RelativeLayout) findViewById(R.id.second_userinfo_layout));
		
		// 데이터 받고 페이지 셋팅
		if (isNetworkAvailableAndNotice()) {
			getCompetitorJSONByThread();
		} else {
			return ;
		}
		
		//축하 관련 애니메이션
		animRing = AnimationUtils.loadAnimation(this, R.anim.select_winner01_celebrate_ring);
		animText = AnimationUtils.loadAnimation(this, R.anim.select_winner01_celebrate_text);
		//animRingSmall = AnimationUtils.loadAnimation(this, R.anim.select_winner01_celebrate_ring_small);
		animPhotoWinner = AnimationUtils.loadAnimation(this, R.anim.select_winner01_celebrate_photo_winner);
		animPhotoLoser = AnimationUtils.loadAnimation(this, R.anim.select_winner01_celebrate_photo_loser);
		animWhole = AnimationUtils.loadAnimation(this, R.anim.select_winner01_celebrate_whole);
		
		//그림을 그릴 수 있는 영역
		v_content_main_outer = (RelativeLayout) findViewById(R.id.content_main_outer);
		
		//우승 축하 애니메이션 이벤트들
		animWhole.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationEnd(Animation animation) {
				isNowAnimation = false;
			}
			@Override
			public void onAnimationRepeat(Animation animation) {
			}
			@Override
			public void onAnimationStart(Animation animation) {
			}
		});
	}
	
	/**
	 * 
	 */
	private void getCompetitorJSONByThread() {
		progressDialog.setMessage("정보를 불러오고있습니다.");
		progressDialog.show();
		
		Runnable runnable = new Runnable(){
			@Override
			public void run() {
				//UI 를 건들기 때문에 핸들러 사용.
				myHandler.post(new Runnable() {
					@Override
					public void run() {
						try {
							
							// DB에 정해진 giftInfo 가져오기
							getGiftInfo();
							
							// 데이터 받고
							getCompetitorJSON();
							
							// 데이터가 있다면 // 페이지 만들기
							if(CompetitorInfoMap.containsKey(currentGroupNum)){
								//btn 클릭리스너
								btn_prev_round = (RelativeLayout) findViewById(R.id.btn_prev_round);
								btn_prev_group = (RelativeLayout) findViewById(R.id.btn_prev_group);
								btn_next_group = (RelativeLayout) findViewById(R.id.btn_next_group);
								btn_next_round = (RelativeLayout) findViewById(R.id.btn_next_round);
								btn_prev_round.setOnClickListener(SlideshowWinner23RoundActivity.this);
								btn_prev_group.setOnClickListener(SlideshowWinner23RoundActivity.this);
								btn_next_group.setOnClickListener(SlideshowWinner23RoundActivity.this);
								btn_next_round.setOnClickListener(SlideshowWinner23RoundActivity.this);
								
								// 자신의 nextround_pass_yn 이 N 이라면 -> 결과 확인 업데이트, 선물의 80% 환급, 이후 결과를 알고 싶다면 포인트 알림 창
								if("N".equals(connectorNextround_pass_yn)) {
									updateConfirm(); // 결과확인 했다구 업데이트 
									refundGiftPrice(); // 선물의 80% 환급
								}
								
								// 그룹이름 변경
								changeGroupAlphabet(currentGroupNum);
								// 첫그룹의 페이지만들기
								setOneGroupLayout(CompetitorInfoMap.get(currentGroupNum));
								// 애니메이션 실행
								displayAnimation(CompetitorInfoMap.get(currentGroupNum));
							} else {
								viewToast("데이터가 없습니다.");
							}
							
						} catch(Exception e) {
							Log.d("tag", e.toString());
						} finally {
							progressDialog.dismiss();
						}
					}
				});
			}
		};
		new Thread(runnable).start();
	}
	
	private void refundGiftPrice() {
		// TODO Auto-generated method stub
		if(connectorGiftid == 0)
			return ;
		
		int refundPrice = (int) (giftInfoList.get(connectorGiftid - 1).getPrice() * 0.8);
		try {
			String jsonText = JsonUtils
					.getStringFromUrl(LovetoConstant.REFUND_PRICE_TO_USER + "?memberid=" + connectorMemberid+"&price=" + refundPrice);
			
			if("T".equals(jsonText)) {
				Log.d("tag", "refundGiftPrice");
			} else {
				Log.d("tag", "do not refundGiftPrice");
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void updateConfirm() {
		// TODO Auto-generated method stub
		try {
			String jsonText = JsonUtils
					.getStringFromUrl(LovetoConstant.PARTICIPANT_CONFIRM_UPDATE + "?tournamentid=" + tournamentID+"&memberid=" + connectorMemberid);
			
			if("T".equals(jsonText)) {
				Log.d("tag", "updateConfirm");
			} else {
				Log.d("tag", "do not updateConfirm");
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void displayAnimation(List<CompetitorInfo> competitorInfoList) {
		// TODO Auto-generated method stub
		// 애니메이션 진행중
		isNowAnimation = true;
		
		// 진출자만 애니메이션 동작하게 하기위해 검색
		int competitorInfoListSize = competitorInfoList.size();
		for(int i=0; i<competitorInfoListSize; i++) {
			if("Y".equals(competitorInfoList.get(i).getNextround_pass_yn())){
				presentWinner = i+1; // 통과한 유저의 index 저장
				Log.d("tag", "presentWinner : " + presentWinner);
				break;
			}
		}
		// 애니메이션 작동
		viewCelebrate();
	}

	private void changeGroupAlphabet(Integer index) {
		ImageView groupAlphabetImageView = (ImageView) findViewById(R.id.img_group_alphabet);
		
		switch(index){
		case 0:
			groupAlphabetImageView.setImageResource(R.drawable.text_info_tournament_group_01);
			break;
		case 1:
			groupAlphabetImageView.setImageResource(R.drawable.text_info_tournament_group_02);
			break;
		case 2:
			groupAlphabetImageView.setImageResource(R.drawable.text_info_tournament_group_03);
			break;
		case 3:
			groupAlphabetImageView.setImageResource(R.drawable.text_info_tournament_group_04);
			break;
		case 4:
			groupAlphabetImageView.setImageResource(R.drawable.text_info_tournament_group_05);
			break;
		case 5:
			groupAlphabetImageView.setImageResource(R.drawable.text_info_tournament_group_06);
			break;
		case 6:
			groupAlphabetImageView.setImageResource(R.drawable.text_info_tournament_group_07);
			break;
		case 7:
			groupAlphabetImageView.setImageResource(R.drawable.text_info_tournament_group_08);
			break;
		}
	}
	
	private void getGiftInfo() {
		try {
			String jsonText = JsonUtils.getStringFromUrl(LovetoConstant.GIFT_LIST);
			//Log.d("tag", "jsonText : " + jsonText);
			JSONArray jsonArray = new JSONArray(jsonText);
			for (int i = 0; i < jsonArray.length();i++) {
				JSONObject object = jsonArray.getJSONObject(i);
				GiftInfo giftInfo = new GiftInfo(object.getInt("giftid"), object.getString("category"), object.getString("category_kor"), object.getString("size"), object.getString("name"), object.getInt("price"), object.getInt("ability"), object.getString("regdate"));
				giftInfoList.add(giftInfo);
			}
		}catch (JSONException e) {
			e.printStackTrace();
			Log.d("tag", "getGiftInfo() error, " + e.getMessage());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			Log.d("tag", "getGiftInfo() error, " + e.getMessage());
		} finally {
		}
	}
	
	private void getTournamentIDAndRoundSeq() {
		// TODO Auto-generated method stub
		// preference
		//로컬에서 정보 받아오기
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		connectorMemberid = pref.getString("memberid", "");
		
		// intent
		Intent intent = getIntent();
		tournamentID = intent.getStringExtra("tournamentID");
		roundSeq = intent.getIntExtra("roundSeq", 0);
		totalCompetitorSize = intent.getIntExtra("totalCompetitorSize", 0);
		firstRoundWinnerIDList = intent.getStringArrayListExtra("firstRoundWinnerIDList");
		secondRoundWinnerIDList = intent.getStringArrayListExtra("secondRoundWinnerIDList");
		thirdoundWinnerIDList = intent.getStringArrayListExtra("thirdoundWinnerIDList");
		fourthRoundWinnerIDList = intent.getStringArrayListExtra("fourthRoundWinnerIDList");
	}
	
	@Override
	public void onBackPressed() {
		new AlertDialog.Builder(SlideshowWinner23RoundActivity.this)
		.setTitle("알림")
		.setMessage("초기 페이지로 갑니다. 가시겠습니까?")
		.setPositiveButton("예", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
		        // TODO Auto-generated method stub
				Intent intent = new Intent(SlideshowWinner23RoundActivity.this, JoinedTournamentListActivity.class);
		  		startActivity(intent);
		        finish();
			}
			
		})
		.setNegativeButton("아니요", null)
		.show();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		// 이벤트가 진행중이면 가만히 있는다.
		if(isNowAnimation)
			return;
		
		// intent
		Intent intent = null;
		
		switch (v.getId()) {
		case R.id.btn_prev_round: // 이전 라운드 버튼
			intent = new Intent(SlideshowWinner23RoundActivity.this, SlideshowWinnerIntermidRoundActivity.class);
			intent.putExtra("tournamentID", tournamentID);
			intent.putExtra("roundSeq", --roundSeq);
			intent.putExtra("totalCompetitorSize", totalCompetitorSize);
			
			intent.putStringArrayListExtra("firstRoundWinnerIDList", firstRoundWinnerIDList);
	  		intent.putStringArrayListExtra("secondRoundWinnerIDList", secondRoundWinnerIDList);
	  		intent.putStringArrayListExtra("thirdoundWinnerIDList", thirdoundWinnerIDList);
	  		intent.putStringArrayListExtra("fourthRoundWinnerIDList", fourthRoundWinnerIDList);
			
			startActivity(intent);
			break;
		case R.id.btn_prev_group: // 이전 그룹 버튼
			if(currentGroupNum > 0) {
				// animation init
				((ImageView)oneMemberLayoutList.get((presentWinner-1)).findViewById(R.id.winner_ring)).setVisibility(ImageView.INVISIBLE);
				((ImageView)oneMemberLayoutList.get((presentWinner-1)).findViewById(R.id.winner_text_celebrate)).setVisibility(ImageView.INVISIBLE);
				
				currentGroupNum--; // 그룹 왼쪽으로 이동
				changeGroupAlphabet(currentGroupNum); // 그룹이름 변경
				setOneGroupLayout(CompetitorInfoMap.get(currentGroupNum)); // 한사람의 페이지  만들기
				displayAnimation(CompetitorInfoMap.get(currentGroupNum)); // 애니메이션 실행
			} else {
				viewToast("페이지 끝입니다.");
			}
			break;
		case R.id.btn_next_group: // 다음 그룹 버튼
			if(currentGroupNum < groupSize-1) {
				// animation init
				((ImageView)oneMemberLayoutList.get((presentWinner-1)).findViewById(R.id.winner_ring)).setVisibility(ImageView.INVISIBLE);
				((ImageView)oneMemberLayoutList.get((presentWinner-1)).findViewById(R.id.winner_text_celebrate)).setVisibility(ImageView.INVISIBLE);
				
				currentGroupNum++;
				changeGroupAlphabet(currentGroupNum);
				setOneGroupLayout(CompetitorInfoMap.get(currentGroupNum)); // 한사람의 페이지  만들기
				displayAnimation(CompetitorInfoMap.get(currentGroupNum)); // 애니메이션 실행
			} else {
				viewToast("페이지 끝입니다.");
			}
			break;
		case R.id.btn_next_round: // 다음 라운드 버튼
			//Log.d("tag", "23진출자 몇명? : "+winnerIDList.size());
			if(winnerIDList.size() == 1) {
				intent = new Intent(SlideshowWinner23RoundActivity.this, SlideshowWinnerCompleteActivity.class);
				
				// 우승자 찾아내기
				CompetitorInfo competitorInfo = null;
				for(int i=0; i<groupSize; i++) {
					Integer competitorInfoListSize = CompetitorInfoMap.get(i).size();
					for(int j=0; j<competitorInfoListSize; j++) {
						if("Y".equals(CompetitorInfoMap.get(i).get(j).getNextround_pass_yn())){
							competitorInfo = CompetitorInfoMap.get(i).get(j);
							break;
						}
					}
				}
				
				// null 이 아니라면
				if(competitorInfo != null) {
					intent.putExtra("memberid", competitorInfo.getRoundparticipant_memberid());
					intent.putExtra("gender", competitorInfo.getGender());
					intent.putExtra("age", competitorInfo.getAge());
					intent.putExtra("job", competitorInfo.getJob());
					intent.putExtra("height", competitorInfo.getHeight());
					intent.putExtra("giftid", competitorInfo.getGiftid());
					intent.putExtra("tournament_maker_memberid", competitorInfo.getTournament_maker_memberid());
				} else {
					viewToast("우승자 에러!!");
				}
				
			} else {
				intent = new Intent(SlideshowWinner23RoundActivity.this, SlideshowWinnerIntermidRoundActivity.class);
				intent.putExtra("roundSeq", ++roundSeq);
				intent.putExtra("totalCompetitorSize", totalCompetitorSize);
				
				switch(roundSeq) {
				case 3:
					thirdoundWinnerIDList = winnerIDList;
					break;
				case 4:
					fourthRoundWinnerIDList = winnerIDList;
					break;
				}
				
				intent.putStringArrayListExtra("firstRoundWinnerIDList", firstRoundWinnerIDList);
		  		intent.putStringArrayListExtra("secondRoundWinnerIDList", secondRoundWinnerIDList);
		  		intent.putStringArrayListExtra("thirdoundWinnerIDList", thirdoundWinnerIDList);
		  		intent.putStringArrayListExtra("fourthRoundWinnerIDList", fourthRoundWinnerIDList);
			}
			intent.putExtra("tournamentID", tournamentID);
			startActivity(intent);
			break;
		default:
			break;
		}
	}
	
	private void setOneGroupLayout(final List<CompetitorInfo> competitorInfoList) {
		progressDialog.setMessage("페이지를 만들고 있습니다.");
		progressDialog.show();
		
		try {
			//init
			for(RelativeLayout oneMemberLayout : oneMemberLayoutList) {
				oneMemberLayout.setVisibility(View.INVISIBLE);
			}
			//make
			for(int i=0; i<competitorInfoList.size(); i++) {
				oneMemberLayoutList.get(i).setVisibility(View.VISIBLE);
				
				StringBuffer sb = new StringBuffer();
				// 참가자사진 셋팅
				sb.append(LovetoConstant.PHOTO_URL);
				sb.append(competitorInfoList.get(i).getRoundparticipant_memberid());
				sb.append("_1.jpg");
				ImageDownloader imageDownloader = new ImageDownloader();// 사진 다운로드
				ImageView imgView = (ImageView) oneMemberLayoutList.get(i).findViewById(R.id.user_photo);
				imageDownloader.download(sb.toString(), imgView);
				
				// 선물사진 셋팅
				imgView = (ImageView) oneMemberLayoutList.get(i).findViewById(R.id.user_gift_photo);
				int giftid = competitorInfoList.get(i).getGiftid();
				imgView.setVisibility(View.VISIBLE);
				//그림에 애니메이션을 넣을지 그림을 넣을지 판단
				if (giftid == 0) {
					// 없는거니 무시
					imgView.setVisibility(View.INVISIBLE);
				} else if (giftAnims.getGiftAnimMap().containsKey(giftid)) { 
					//로컬에 선물 아이디에 대한 애니메이션 리소스가 있으면
					imgView.setBackgroundResource(giftAnims.getGiftAnimMap().get(giftid)); //애니메이션 지정
					giftAnimList.add((AnimationDrawable)imgView.getBackground()); //애니메이션 배열에 추가 (나중에 한번에 start 하기 위해)
				} else {
					//현재 버전에 선물에 대한 애니메이션 리소스가 없으면 FTP 의 1장짜리 이미지로 대체함
					sb.setLength(0);
					sb.append(LovetoConstant.GIFT_IMAGE_URL);
					sb.append(giftid);
					sb.append(".png");
					imageDownloader.download(sb.toString(), imgView);
				}
				
				// 참가자 아이디
				TextView textView = (TextView) oneMemberLayoutList.get(i).findViewById(R.id.user_id);
				textView.setText(competitorInfoList.get(i).getRoundparticipant_memberid());
				
				// 참가자 아이디 그림자
				textView = (TextView) oneMemberLayoutList.get(i).findViewById(R.id.user_id_shadow);
				textView.setText(competitorInfoList.get(i).getRoundparticipant_memberid());
				
				// 참가자답변
				textView = (TextView) oneMemberLayoutList.get(i).findViewById(R.id.user_comment);
				textView.setText(competitorInfoList.get(i).getAnswer_content());
				
				// InfoLayout들 셋팅
				// 텍스트 셋팅
				textView = (TextView) oneMemberInfoLayoutList.get(i).findViewById(R.id.ability_textview);
				// 선물사진 셋팅
				imgView = (ImageView) oneMemberInfoLayoutList.get(i).findViewById(R.id.gift_imageview);
				//그림에 애니메이션을 넣을지 그림을 넣을지 판단
				if (giftid == 0) { // 없는거니 무시
					imgView.setBackgroundResource(R.drawable.gift_empty);
					textView.setText("");
				} else if (giftAnims.getGiftAnimMap().containsKey(giftid)) {
					sb.setLength(0);
					sb.append(giftInfoList.get(giftid-1).getCategory_kor());
					sb.append("+");
					sb.append(giftInfoList.get(giftid-1).getAbility());
					textView.setText(sb.toString());
					
					//로컬에 선물 아이디에 대한 애니메이션 리소스가 있으면
					imgView.setBackgroundResource(giftAnims.getGiftAnimMap().get(giftid)); //애니메이션 지정
					//giftAnimList.add((AnimationDrawable)imgView.getBackground()); //애니메이션 배열에 추가 (나중에 한번에 start 하기 위해)
				} else {
					sb.setLength(0);
					sb.append(giftInfoList.get(giftid-1).getCategory_kor());
					sb.append("+");
					sb.append(giftInfoList.get(giftid-1).getAbility());
					textView.setText(sb.toString());
					
					//현재 버전에 선물에 대한 애니메이션 리소스가 없으면 FTP 의 1장짜리 이미지로 대체함
					sb.setLength(0);
					sb.append(LovetoConstant.GIFT_IMAGE_URL);
					sb.append(giftid);
					sb.append(".png");
					imageDownloader.download(sb.toString(), imgView);
				}
				
				// 참가자 나이
				textView = (TextView) oneMemberInfoLayoutList.get(i).findViewById(R.id.userinfo_text_age);
				textView.setText("나이: "+competitorInfoList.get(i).getAge());
				// 참가자 키
				textView = (TextView) oneMemberInfoLayoutList.get(i).findViewById(R.id.userinfo_text_height);
				textView.setText("키: "+competitorInfoList.get(i).getHeight());
				// 참가자 직업
				textView = (TextView) oneMemberInfoLayoutList.get(i).findViewById(R.id.userinfo_text_job);
				textView.setText("직업: "+competitorInfoList.get(i).getJob());
			}
		} catch(Exception e) {
			Log.d("tag", e.toString());
		} finally {
			progressDialog.dismiss();
		}
	}
	
	private void getCompetitorJSON() {
		try {
			String jsonText = JsonUtils
					.getStringFromUrl(LovetoConstant.SELECT_WINNER_ROUND + "?tournamentid=" + tournamentID+"&roundseq=" + roundSeq);
			//Log.d("tag", jsonText);

			JSONArray jsonArrayByGroup = new JSONArray(jsonText);
			groupSize = jsonArrayByGroup.length();
			for(int i=0; i<groupSize; i++) {
				JSONObject objectByGroup = jsonArrayByGroup.getJSONObject(i);
				Integer groupNum = objectByGroup.getInt("group");
				JSONArray jsonArray = objectByGroup.getJSONArray("list");
				
				List<CompetitorInfo> competitorInfoList = new ArrayList<CompetitorInfo>();
				//Log.d("tag", "길이는 : "+ jsonArray.length());
				for(int j=0; j<jsonArray.length(); j++) {
					JSONObject object = jsonArray.getJSONObject(j);
					CompetitorInfo competitorInfo = new CompetitorInfo(
						object.getString("roundparticipant_memberid"),
						object.getString("answer_endtime"),
						object.getString("regdate"),
						object.getString("photo_url1"),
						object.getString("local"),
						object.getString("age"), 
						object.getString("gender"),
						object.getString("answer_content"),
						object.getString("nextround_pass_yn"),
						object.getString("height"),
						object.getString("job"),
						object.getInt("giftid"), 
						object.getString("tournament_maker_memberid")
					);
					
					// 접속자와 아이디가 같으면  Nextround_pass_yn 셋팅 // 80%환불과 결과반영을 위해
					if(connectorMemberid.equals(object.getString("roundparticipant_memberid"))) {
						connectorNextround_pass_yn = object.getString("nextround_pass_yn");
						connectorGiftid = object.getInt("giftid");
						
						// 접속자의 그룹 저장 // 접속자 그룹 먼저 보여주기 위해
						currentGroupNum = i;
					}
					
					// 진출자 저장 후 다음 액티비티로 넘김 // 이유 : 미들 페이지 구현을 위해
					if("Y".equals(object.getString("nextround_pass_yn"))) {
						winnerIDList.add(object.getString("roundparticipant_memberid"));
					}
					
					competitorInfoList.add(competitorInfo);
				}
				// data 저장
				CompetitorInfoMap.put(groupNum-1, competitorInfoList);
			}
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//승자에대한 연출을 보여줌.
	private void viewCelebrate() {
		//화면 전체 갱신을 위한 에니매이션
		v_content_main_outer.startAnimation(animWhole);
		
		//승자의 애니메이션 연출
		((ImageView)oneMemberLayoutList.get((presentWinner-1)).findViewById(R.id.winner_ring)).setVisibility(ImageView.VISIBLE);
		((ImageView)oneMemberLayoutList.get((presentWinner-1)).findViewById(R.id.winner_ring)).startAnimation(animRing);
		((ImageView)oneMemberLayoutList.get((presentWinner-1)).findViewById(R.id.winner_text_celebrate)).setVisibility(ImageView.VISIBLE);
		((ImageView)oneMemberLayoutList.get((presentWinner-1)).findViewById(R.id.winner_text_celebrate)).startAnimation(animText);
		((ImageView)oneMemberLayoutList.get((presentWinner-1)).findViewById(R.id.user_photo)).startAnimation(animPhotoWinner);
		
		//패자의 애니메이션 연출
		for(int i=0;i<oneMemberLayoutList.size();i++) {
			if (i != (presentWinner-1)) {
				((ImageView)oneMemberLayoutList.get(i).findViewById(R.id.user_photo)).startAnimation(animPhotoLoser);
			}
		}
		
	}
}
